<template>
    <div>
        <video ref="remoteVideo" autoplay playsinline></video>
        <button @click="startViewing">开始观看</button>
    </div>
</template>

<script setup>
import { ref } from 'vue'

const remoteVideo = ref(null)
let socket = null
let peerConnection = null

const startViewing = async () => {
    try {
        // 先建立WebSocket连接
        socket = new WebSocket('ws://192.168.3.155:8080/websocket')

        // 等待连接就绪
        await new Promise((resolve, reject) => {
            socket.onopen = resolve
            socket.onerror = reject
            setTimeout(() => reject(new Error('连接超时')), 5000)
        })

        // 现在可以安全发送注册
        socket.send(JSON.stringify({
            type: 'register',
            role: 'receiver'
        }))

        // 2. 初始化PeerConnection
        peerConnection = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' },
                // 可在此添加TURN服务器
            ]
        })

        // 3. 处理远程流
        peerConnection.ontrack = (event) => {
            remoteVideo.value.srcObject = event.streams[0]
        }

        // 4. ICE候选处理
        peerConnection.onicecandidate = (event) => {
            if (event.candidate) {
                socket.send(JSON.stringify({
                    type: 'candidate',
                    candidate: event.candidate,
                    target: 'sender'
                }))
            }
        }

        // 5. 信令处理
        socket.onmessage = async (event) => {
            const data = JSON.parse(event.data)

            //重要步骤开始信令交流
            if (data.type === 'offer') {
                // 接收到推流端的offer
                await peerConnection.setRemoteDescription(data)
                // 拉流端创建answer
                const answer = await peerConnection.createAnswer()
                // 这步骤很重要，拉流端需要用peerConnection.setLocalDescription()设置创建的answer
                await peerConnection.setLocalDescription(answer)
                // 推流端把answer里的sdp发送给拉流端
                socket.send(JSON.stringify({
                    type: 'answer',
                    sdp: answer.sdp,
                    target: 'sender'
                }))
            }
            else if (data.type === 'candidate') {
                await peerConnection.addIceCandidate(data.candidate)
            }
        }
    } catch (error) {
        console.error('观看失败:', error)
    }
}
</script>